import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance } from 'vue'
import goodsProject from '@/api/inwarehouse/goodsProject'
import projectApi from '@/api/inwarehouse/project-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'
import goodsApi from '@/api/inwarehouse/goods-api'
import { ElMessage } from 'element-plus'

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const typeOptions = [
      { value: '0', label: '挪用' },
      { value: '1', label: '归还' }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '紧急挪用',
      api: goodsProject,
      columns: [
        { prop: 'type', label: '类型', width: 90, slot: true },
        { prop: 'name', label: '原始项目', width: 300 },
        { prop: 'nameNew', label: '目标项目', width: 300 },
        { prop: 'skuName', label: '物料名称', valueType: 'input' },
        { prop: 'barCode', label: '物料编码', valueType: 'input', width: 120 },
        { prop: 'number', label: '挪用数量', width: 100},
        { prop: 'operation', label: '操作', slot: true, width: 150 }
      ],
      rules: {
        type: [{ required: true, message: '请选择挪用状态', trigger: 'change' }],
        name: [{ required: true, message: '请选择原始项目', trigger: 'change' }],
        nameNew: [{ required: true, message: '请选择目标项目', trigger: 'change' }]
      },
      other: {
        getTypeName(val: string) {
          const obj = typeOptions.find(item => {
            return item.value == val
          })
          if(obj) {
            return obj['label']
          }
          return '-'
        },
        addGoods() {
          if (!ctx.editData['orderGoodsList']) {
            ctx.editData['orderGoodsList'] = []
          }
          ctx.editData['orderGoodsList'].push({})
        },
        delGoods() {
          data.delGoodsList.map(dgl => {
            const index = ctx.editData['orderGoodsList'].findIndex(item => {
              return item.id === dgl.id
            })
            ctx.editData['orderGoodsList'].splice(index, 1)
          })
        },
        handleGoodsSelectionChange(val: any) {
          // console.log(val)
          if (!ctx.editData['orderGoodsList']) {
            return
          }
          data.delGoodsList = val
        },
        save() {
          const {
            type,
            name,
            nameNew,
            orderGoodsList
          } = ctx.editData
          if(!orderGoodsList || orderGoodsList.length === 0 || data.finishLoading) {
            return
          }
          data.finishLoading = true;
          const arr = [];
          orderGoodsList.map(ogl => {
            if(ogl.number && ogl.number > 0) {
              arr.push(ogl)
            }
          })
          arr.map(async (ar, index) => {
            const params = {
              type,
              name,
              nameNew,
              ...ar
            }
            const res = await goodsProject.save(params);
            data.finishLoading = false;
            if(res.success && index === arr.length - 1) {
              ElMessage.success('新增成功');
              ctx.loadData()
              ctx.editVisible = false;
            }
          })
        }
      }
    }))

    const getProjectList = async() => {
      const params = { filter: { disabled: 2 } }
      const res = await projectApi.list(params)
      data.projectOptions = res.data.records
    }
    
    const getGoodsList = async (val: string) => {
      data.loading = true;
      const params = { otherFilter: { skuName: val } }
      const res = await goodsApi.list(params)
      data.loading = false;
      data.goodsOptions = res.data.records;
    }

    const handleSkuChange = (val, scope) => {
      const obj = data.goodsOptions.find(item => {
        return item.skuName === val
      })
      getInventoryList(obj, scope)
    }

    const getInventoryList = async (obj: any, scope: any) => {
      const params = {filter: {barCode: obj.barCode}}
      const res = await goodsApi.list(params)
      const inventoryList = res.data.records;
      obj['inventoryList'] = inventoryList;
      obj['number'] = 0;
      if(scope.row.barCode) {
        const index = ctx.editData.orderGoodsList.findIndex(item => item.barCode === scope.row.barCode);
        ctx.editData.orderGoodsList.splice(index, 1, obj);
      } else {
        Object.assign(scope.row, obj);
      }
      data.goodsOptions = [{...obj}];
    }

    // init
    onMounted(() => {
      getProjectList()
      ctx.loadData()
    })

    const data = reactive({
      ctx,
      typeOptions,
      projectOptions: [],
      delGoodsList: [],
      loading: false,
      goodsOptions: [],
      finishLoading: false,
      getGoodsList,
      handleSkuChange
    })

    return {
      ...toRefs(data)
    }
  }
})
